﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace WebberCross.JavaScriptBridge.JSBridgeDemoApp.ViewModels
{
    public class JSBridgeDemoViewModel : ViewModelBase, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler  PropertyChanged;

        private string _text = "No message";
        private RelayCommand _sendCommand = null;

        public string Text
        {
            get { return this._text; }
            set 
            {
                if(this._text != value)
                {
                    this._text = value;
                    if(this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs("Text"));
                }
            }
        }

        public ICommand SendCommand
        {
            get
            {
                if (_sendCommand == null)
                {
                    _sendCommand = new RelayCommand(
                        param => this.SendMessage(),
                        param => true
                        );
                }
                return _sendCommand;
            }
        }

        private void SendMessage()
        {
            try
            {
                // Send a message to the bridge
                DemoMessage msg = new DemoMessage("Hello from Silverlight Application", base._jsClientID.ToString());
                string jsonMsg = JSONHelper.Serialize(msg);
                base.JSBridgeSend(jsonMsg);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        // Override base JSBridgeReceive method
        public override void JSBridgeReceive(string arg)
        {
            try
            {
                // Deserialize message
                DemoMessage msg = JSONHelper.Deserialize<DemoMessage>(arg);

                // Write message to label
                this.Text = string.Format("{0}, from JSBridge Client {1}", msg.Message, msg.JSClientID);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
